#include "stdafx.h"
#include "DepthStencil.h"

namespace Reign
{namespace Video
{namespace D3D10
{
	#pragma region Properties
	ID3D10DepthStencilView* DepthStencil::Surface::get() {return surface;}
	#pragma endregion

	#pragma region Constructors
	DepthStencil::DepthStencil(DisposableI^ parent, int width, int height, DepthStenicFormats depthStenicFormats)
	: Disposable(parent)
	{
		null();
		try
		{
			video = parent->FindParentOrSelfWithException<Video^>();
		
			//Texture
			D3D10_TEXTURE2D_DESC descDepth;
			ZeroMemory(&descDepth, sizeof(D3D10_TEXTURE2D_DESC));
			descDepth.Width = width;
			descDepth.Height = height;
			descDepth.MipLevels = 1;
			descDepth.ArraySize = 1;
			descDepth.Format = DXGI_FORMAT_D32_FLOAT;//DXGI_FORMAT_D24_UNORM_S8_UINT;
			descDepth.SampleDesc.Count = 1;
			descDepth.SampleDesc.Quality = 0;
			descDepth.Usage = D3D10_USAGE_DEFAULT;
			descDepth.BindFlags = D3D10_BIND_DEPTH_STENCIL;
			descDepth.CPUAccessFlags = 0;
			descDepth.MiscFlags = 0;
			ID3D10Texture2D* textureTEMP;
			if (FAILED(video->Device->CreateTexture2D(&descDepth, 0, &textureTEMP)))
			{
				Debug::ThrowError(L"DepthStencil", L"Failed to create Texture2D");
			}
			texture = textureTEMP;
		
			//DepthStencil
			D3D10_DEPTH_STENCIL_VIEW_DESC descDSV;
			ZeroMemory(&descDSV, sizeof(D3D10_DEPTH_STENCIL_VIEW_DESC));
			descDSV.Format = descDepth.Format;
			if (descDepth.SampleDesc.Count > 1) descDSV.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2DMS;
			else descDSV.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D;
			descDSV.Texture2D.MipSlice = 0;
			ID3D10DepthStencilView* surfaceTEMP;
			if (FAILED(video->Device->CreateDepthStencilView(texture, &descDSV, &surfaceTEMP)))
			{
				Debug::ThrowError(L"DepthStencil", L"Failed to create DepthStencilView");
			}
			surface = surfaceTEMP;
		
			if (texture) texture->Release(); texture = 0;
		}
		catch (Exception^ ex)
		{
			delete this;
			throw ex;
		}
	}

	DepthStencil::~DepthStencil()
	{
		disposeChilderen();
		if (texture) texture->Release();
		if (surface) surface->Release();
		null();
	}

	void DepthStencil::null()
	{
		texture = 0;
		surface = 0;
	}
	#pragma endregion
}
}
}